package com.start.common.mybaitsplus;

import com.start.common.enums.StartBaseEnum;
import com.start.common.enums.StartBaseStringEnum;
import com.start.common.tools.StartEnumTools;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GlobalMyBaitsStartStringEnumTypeHandler extends BaseTypeHandler<StartBaseStringEnum> {
    private Class<? extends StartBaseStringEnum> clazz = null;

    public GlobalMyBaitsStartStringEnumTypeHandler(Class<? extends StartBaseStringEnum> clazz) {
        assert clazz != null;
        assert clazz.isEnum();
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, StartBaseStringEnum startBaseStringEnum, JdbcType jdbcType) throws SQLException {
        String value = startBaseStringEnum.getValue();
        preparedStatement.setString(i, value);

    }

    @Override
    public StartBaseStringEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (resultSet == null) return null;
        String string = resultSet.getString(s);
        if (StringUtils.isEmpty(string)) return null;
        StartBaseEnum enumByValue = StartEnumTools.findEnumByValue(clazz, string);
        return (StartBaseStringEnum) enumByValue;
    }

    @Override
    public StartBaseStringEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if (resultSet == null) return null;
        String value = resultSet.getString(i);
        if(value==null||StringUtils.isEmpty(value))return null;
        StartBaseStringEnum[] enumConstants = clazz.getEnumConstants();
        for (StartBaseStringEnum e:enumConstants) {
            if(e.getValue().equals(value))return e;
        }
        return null;
    }

    @Override
    public StartBaseStringEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        if (callableStatement == null) return null;
        String value = callableStatement.getString(i);
        if(value==null||StringUtils.isEmpty(value))return null;
        StartBaseStringEnum[] enumConstants = clazz.getEnumConstants();
        for (StartBaseStringEnum e:enumConstants) {
            if(e.getValue().equals(value))return e;
        }
        return null;
    }
}
